package org.leo.dm.example.reader;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.leo.dm.common.bean.StepResultBean;
import org.leo.dm.common.exception.DpException;
import org.leo.dm.common.exception.DpExceptionCodeEnum;
import org.leo.dm.component.reader.Reader;
import org.leo.dm.component.util.DbManager;
import org.leo.dm.util.ToUtil;

public class ProduceDbDataReader extends Reader {
	private String sourceName;
	protected Connection conn;

	public void setConn(Connection conn) {
		this.conn = conn;
	}

	public String getSourceName() throws Exception {
		if (sourceName == null) {
			getFlow().stop();
			throw new DpException(DpExceptionCodeEnum.PARAM_ERROR, "数据来源名称不能为空");
		}
		return sourceName;
	}

	public void setSourceName(String sourceName) {
		this.sourceName = sourceName;
	}

	@Override
	public StepResultBean call() {
		StepResultBean resultBean = new StepResultBean();
		try {
			getCount();
			produceData(getSourceName());

			String queueNumber = UUID.randomUUID().toString();
			storage.setStorageName(queueNumber);

			storage.putStartQueue(queuePlugin.handle(storage.getStorageName()), null);

			segmentPlugin.handle(getSourceName());
			storage.putStartSeqment(1, getSourceName(), dataNames, null);
			seqmentcounter = 0;

			String[] dataValuesTemp = null;
			for (int i = 0; i < this.getRowCount(); i++) {
				counter++;// 计数器累加
				seqmentcounter++;// 段计数器累加
				dataValuesTemp = new String[dataValues.length];
				for (int si = 0; si < dataValues.length; si++) {
					dataValuesTemp[si] = columnPlugin.handle(getSourceName(), dataNames[si], dataValues[si]);
				}
				storage.putData(recordPlugin.handle(getSourceName(), dataNames, dataValuesTemp, seqmentcounter));
			}

			storage.putEndSeqment(1);
			storage.putEndQueue();

			ToUtil.to("数据抽取执行完成");

			Map<String, Object> callBackMap = new HashMap<String, Object>();
			callBackMap.put("counter", counter);
			callBack.handle(callBackMap);

			resultBean.setCode("1");
			resultBean.setName("运行正常完成");
			resultBean.setSuccessCount(counter);
		} catch (Exception e) {
			e.printStackTrace();
			resultBean.setCode("-1");
			resultBean.setName("运行发生异常");
			try {
				this.getFlow().stop();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {

			counter = 0;// 计数器清零
		}

		return resultBean;
	}

	/**
	 * 
	 * Created on 2015年11月11日 .
	 * 
	 * @author xiao_h 获取总数
	 */
	private void getCount() {
		try {
			ToUtil tu1 = new ToUtil();

			ToUtil.to("count:" + rowCount);
			tu1.takeTimePrex("获取记录数花费时间");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				this.getFlow().stop();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	private void produceData(String tableName) {
		PreparedStatement pst = null;
		try {
			pst = conn.prepareStatement("select * from " + tableName + " where 1=2");
			ResultSetMetaData rsd = pst.executeQuery().getMetaData();

			int rt = rsd.getColumnCount();
			String[] dataNamesTemp = new String[rt];
			String[] dataValuesTemp = new String[rt];
			for (int i = 0; i < rt; i++) {
				// log.info("java类型：" + rsd.getColumnClassName(i + 1) + " 数据库类型:" + rsd.getColumnTypeName(i + 1) + " 字段名称:" + rsd.getColumnName(i + 1) + " 字段长度:" + rsd.getColumnDisplaySize(i + 1));
				dataNamesTemp[i] = rsd.getColumnName(i + 1);
				dataValuesTemp[i] = genRandomNum(rsd.getColumnDisplaySize(i + 1) / 5);
				// dataValuesTemp[i] = "1";
			}

			this.setDataNames(dataNamesTemp);
			this.setDataValues(dataValuesTemp);

		} catch (Exception e) {
			e.printStackTrace();
			try {
				this.getFlow().stop();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			DbManager.close(null, pst, null);
		}
	}

	private static String genRandomNum(int pwdLen) {
		final int maxNum = 36;
		int i; // 生成的随机数
		int count = 0; // 生成的密码的长度
		char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < pwdLen) {
			i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}
		return pwd.toString();
	}

}
